<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" style="display: none" v-model="zid" />
      <input type="text" v-model.trim="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.trim="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arrList" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="bianji(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
// 一定一定要记得 数据驱动视图
export default {
  data() {
    return {
      zid: "",
      uname: "",
      age: "",
      gender: "男",
      isemit: false,
      arrList: [
        {
          id: 1,
          uname: "张曼玉",
          age: 17,
          gender: "女",
        },
        {
          id: 2,
          uname: "林青霞",
          age: 17,
          gender: "女",
        },
        {
          id: 3,
          uname: "张杰",
          age: 17,
          gender: "男",
        },
      ],
    };
  },
  methods: {
    //删除函数
    del(id) {
      this.arrList.forEach((item, index) => {
        if (item.id === id) {
          this.arrList.splice(index, 1);
        }
      });
    },
    bianji(id) {
      this.isemit = true;
      const res = this.arrList.find((item) => item.id === id);
      this.uname = res.uname;
      this.age = res.age;
      this.gender = res.gender;
      this.zid = res.id;
    },
    add() {
      if (this.isemit === false) {
        if (this.uname === "" || this.age === "") {
          return alert("输入不能为空");
        } else {
          this.arrList.push({
            id: +new Date(),
            uname: this.uname,
            age: this.age,
            gender: this.gender,
          });
          (this.uname = ""), (this.age = ""), (this.gender = "男");
        }
      } else {
        const res1 = this.arrList.find((item) => item.id === this.zid);
        res1.uname = this.uname;
        res1.age = this.age;
        res1.gender = this.gender;
        this.uname = ""
        this.age = ""
        alert("修改成功")
        this.isemit = false
      }
    },
  },
};
</script>
